<template>
  <van-nav-bar title="登录" left-arrow @click-left="onClickLeft" />

  <div class="login">
    <h2>用户登录</h2>
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field v-model="loginData.phone" required type="tel" center name="手机号" label="手机号" placeholder="请输入手机号"
          maxlength="11" :rules="[
            { required: true, message: '请填写手机号' },
            { validator: checkUserName, message: '手机号格式有误' }
          ]" />

        <van-field v-model="loginData.password" required center type="password" name="密码" label="密码"
          placeholder="密码6-20位，至少包含2种字母、数字、特殊符号" maxlength="20" :rules="[
            { required: true, message: '请填写密码' },
            { validator: checkPwd, message: '密码6-20位，至少包含2种字母、数字、特殊符号' }
          ]" />
      </van-cell-group>

      <van-button round block class="submit" native-type="submit">
        提交
      </van-button>
    </van-form>
  </div>
</template>

<script setup>
import { reactive, toRefs, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { login } from '@/request/api/api.js'

import { storeToRefs } from 'pinia'
import { userStore } from '@/store/user/index.js'
import cookie from 'js-cookie'

const $router = useRouter();

const $userStore = userStore();
let { userInfo, token } = storeToRefs($userStore);


let data = reactive({
  loginData: {
    phone: '',
    password: ''
  },
})

const { loginData } = toRefs(data);

// 登录按钮
const onSubmit = async () => {
  await login(loginData.value).then(data => {
    $userStore.$patch(state => {
      state.token = data.token;
      state.userInfo = data.profile;
    })
    $router.push('/user')
  })
}


// 校验规则
const checkUserName = (val) => {
  if (!/^((1[3,5,8,7,9][0-9])|(14[5,7])|(17[0,6,7,8])|(19[1,7]))\d{8}$/.test(val)) {
    return false;
  }
}

const checkPwd = (val) => {
  if (!/^(?=.*\d)(?=.*[a-zA-Z])(?=.*[^\da-zA-Z\s]).{6,20}$/.test(val)) return false;
}




// 返回按钮
const onClickLeft = () => {
  $router.go(-1)
}

</script>
  
<style lang='less' >
.login {
  width: 90%;
  margin-top: 20px;
  text-align: center;
  margin: 0 auto;

  .van-form {
    margin-top: 50px;

    .van-cell-group--inset {
      margin: 0;
    }

    .submit {
      margin-top: 40px;
    }
  }

}
</style>